# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .MyIO import *
from .ConnFreeswitch import *
from .MySqlite import *

config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"
selectsql="select id,groupname,destination_number,user_number,sort from pbx_group ORDER BY sort"

class GroupDialAdmin(object):
    show_terminal = True
    list_display = ['groupname', 'destination_number', 'user_number']
    list_per_page = 10
    add_form_template = 'GroupEdit.html'
    change_form_template = 'GroupEdit.html'
    search_fields = ['groupname', 'destination_number', 'user_number']

    def valid_forms(self):
    #    srterror = str(self.get_error_list())
     #   if srterror <>'':
      #      self.message_user(u'打*字段必填,别名和表达式必须唯一', 'error')
       # else:
        print str(self.get_error_list())
        return self.form_obj.is_valid()

    def save_models(self):
        obj = self.new_obj
        urllist = str(self.request.get_full_path()).split('/')
        destination_number = obj.destination_number.replace("d", "\d")
        if (str(self.form_obj.data).find('onfail') == -1):  # 查找是否选择了权限
            onfail = ''
        else:
            onfail = str(self.form_obj.data)[str(self.form_obj.data).index('onfail'):].split("]")[0].replace("onfail': [", "").replace("u'", "").replace(" ","").replace("'","")
        if len(urllist) == 5:
            sql = "INSERT INTO pbx_group(groupname,destination_number,user_number,TIMEOUT,onfail,failnum,sort)" \
                  "VALUES('" + obj.groupname + "','" + destination_number + "','"+obj.user_number+"',"\
                  +str(obj.TIMEOUT)+",'"+onfail+"','"+obj.failnum+"','" + str(obj.sort) + "')"
        else:
            sql = "update pbx_group set groupname='"+obj.groupname+"',destination_number='"+destination_number+"' " \
                  ",user_number='"+obj.user_number+"',TIMEOUT='"+str(obj.TIMEOUT)+"',failnum='"\
                  +obj.failnum+"',onfail='"+onfail+"',sort='"+str(obj.sort)+"' where id="+urllist[3]
        ComSql(sql)
        writeGroup(selectsql)
        r = ReloadXml()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

    def delete_models(self, obj):
        obj.delete()
        writeGroup(selectsql)
        r = Reloadacl()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

def writeGroup(strsql):
    info = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'group.xml'))
    strcontent = ""
    aclList = ReadSql(strsql)
    for i in aclList:
        if i[3].find(",")>0:
            user_number = "user/"+i[3].replace(",", ",user/")
        else:
            user_number = "user/" + i[3].replace("|", "|user/")
        strcontent += info.replace('{name}', i[1]).replace("{destination_number}",i[2]).replace("{user_number}", user_number)+"\r\n"
    strDefault = ReadFile(config_file_patch + "dialplan/default.xml")
    intBegin = strDefault.find("<!-- Local GroupDial begin -->")
    intend = strDefault.find("<!-- Local GroupDial end -->")
    strBefin = strDefault[:intBegin] + "<!-- Local GroupDial begin -->"
    strEnd = strDefault[intend:]
    strcontent = strBefin + "\r\n" + strcontent + strEnd
    WriteFile(config_file_patch + "dialplan/default.xml", strcontent)